package com.google.gwt.sample.json.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Composite;

import org.gwtwidgets.client.util.WindowUtils;

import com.google.gwt.user.client.HTTPRequest;
import com.google.gwt.user.client.ResponseTextHandler;

public class MainPage implements EntryPoint {

	public class JSONResponseTextHandler implements ResponseTextHandler {		
		public void onCompletion(String responseText) {
			try {
				JSONValue jsonValue = JSONParser.parse(responseText);
				if (jsonValue != null){
					JSONArray jsonArray = jsonValue.isArray();
					if (jsonArray != null) {
						entry.updateEntry(jsonArray.get(0));
					}					
				}
			} catch (JSONException e) {
			}
		}
	}

	private static VerticalPanel verticalPanel = new VerticalPanel();
	private EntryPanel entry;		
	public void onModuleLoad() {
		String workshopId = WindowUtils.getLocation().getParameter("workshopId");
		if(workshopId != null){
			entry = new WorkshopEntry();
			String searchText = "/python/workshop?workshopId=" + workshopId;
			HTTPRequest.asyncGet(searchText, new JSONResponseTextHandler());
		}
		String codeId = WindowUtils.getLocation().getParameter("codeId");
		if(codeId != null){
			entry = new CodeEntry();
			String searchText = "/python/codesample?codeId=" + codeId;
			HTTPRequest.asyncGet(searchText, new JSONResponseTextHandler());
		}
		if((workshopId == null) && (codeId == null))
			entry = new WorkshopEntry();
		
		final Header header = new Header();

		RootPanel rootPanel = RootPanel.get();
		rootPanel.setWidth("700px");

		final VerticalPanel verticalPanel2 = new VerticalPanel();
		rootPanel.add(verticalPanel);
		verticalPanel2.setWidth("700px");
		verticalPanel2.add(header);

		rootPanel.add(verticalPanel2);
		verticalPanel2.add(verticalPanel);
		verticalPanel.add(entry);	
	}
	static public void setMainPanel(Composite mainPanel, boolean clearMainPage){ 
		if(clearMainPage)
			verticalPanel.clear();
		verticalPanel.add(mainPanel);
	}
}
